package main

//https://stackoverflow.com/questions/37473201/is-there-a-way-to-update-the-tls-certificates-in-a-net-http-server-without-any-d
import (
	"crypto/tls"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"sync"
)

type keypairReloader struct {
	certMu   sync.RWMutex
	cert     *tls.Certificate
	certPath string
	keyPath  string
}

func NewKeypairReloader(certPath, keyPath string) (*keypairReloader, error) {
	result := &keypairReloader{
		certPath: certPath,
		keyPath:  keyPath,
	}
	cert, err := tls.LoadX509KeyPair(certPath, keyPath)
	if err != nil {
		return nil, err
	}
	result.cert = &cert
	//go func() {
	//	c := make(chan os.Signal, 1)
	//	signal.Notify(c, syscall.SIGHUP)
	//	for range c {
	//		g.Log().Printf(ctx, "Received SIGHUP, reloading TLS certificate and key from %q and %q", certPath, keyPath)
	//		if err := result.maybeReload(); err != nil {
	//			g.Log().Printf(ctx, "Keeping old TLS certificate because the new one could not be loaded: %v", err)
	//		}
	//	}
	//}()
	return result, nil
}

func (kpr *keypairReloader) maybeReload() error {
	newCert, err := tls.LoadX509KeyPair(kpr.certPath, kpr.keyPath)
	if err != nil {
		return err
	}
	kpr.certMu.Lock()
	defer kpr.certMu.Unlock()
	kpr.cert = &newCert
	g.Log().Info(ctx, "ssl 加载成功！")
	return nil
}

func (kpr *keypairReloader) GetCertificateFunc() func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
	return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		kpr.certMu.RLock()
		defer kpr.certMu.RUnlock()
		return kpr.cert, nil
	}
}

var kpr *keypairReloader

func UpdateSsl(certPath, keyPath string, s *ghttp.Server) error {
	var err error
	kpr, err = NewKeypairReloader(certPath, keyPath)
	if err != nil {
		return err
	}
	var ssl_tls = &tls.Config{
		MinVersion: tls.VersionTLS12,
		MaxVersion: tls.VersionTLS13,
	}
	ssl_tls.GetCertificate = kpr.GetCertificateFunc()
	s.SetTLSConfig(ssl_tls)
	s.EnableHTTPS(certPath, keyPath, ssl_tls)
	return nil
}

func ReloadSSL() error {
	if kpr == nil {
		return nil
	}
	return kpr.maybeReload()
}
